﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;
using System.IO;
using System.Drawing;
using System.Threading;
using Google.Protobuf.WellKnownTypes;


namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    /// 外协挑库_获取ERP分配库存
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ERPGetStockOutPutController : ControllerBase
    {
        private readonly ILogger _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;
        public readonly string gz_con;


        public ERPGetStockOutPutController(ILogger<ERPGetStockOutPutRequestDto> logger, IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration, ILoggerFactory loggerFactory)
        {
            _WMSTokenCheckService = wmsTokenCheckService;
            con = _configuration.GetConnectionString("DDM_DbConnection_ZH");
            gz_con = _configuration.GetConnectionString("GZ_WMS_DbConnection");
            _logger = loggerFactory.CreateLogger<ERPGetStockOutPutController>();

        }

        /// <summary>
        /// 外协挑库_获取ERP分配库存
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostGetERPKC([FromBody] ERPGetStockOutPutRequestDto strparm)
        {
            string  strMsg = "";
            object log = "";
            log = strparm;
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            ERPGetStockOutPutResponseDto re = new ERPGetStockOutPutResponseDto();
            List<ERPGetStockOutPutResponseData> details = new List<ERPGetStockOutPutResponseData>();


            if (strparm.shipment_no == "")
            {
                
                strMsg = "shipment_no不能为空，运算失败！";
            }
            if (strparm.location_code == "")
            {

                strMsg = "location_code 不能为空，运算失败！";
            }



            Dictionary<string, string> dic = new Dictionary<string, string>(); //查询公用dic
            try
            {
                if (strMsg == "")
                {
                    //获取订单明细，料号、需求数量信息，去获取ERP库存
                    dic = new Dictionary<string, string>();
                    dic.Add("shipment_no", strparm.shipment_no);
                    DataTable hz_dt = MethodHelp.GetTableInfo("TMS0138", dic,con);
                    if (hz_dt.Rows.Count>0)
                    {
                        string mtr = "";
                        foreach (DataRow row in hz_dt.Rows)
                        {
                            mtr = row["material_code"].ToString()+","+ mtr;

                            //校验当前单据，每个料号库存是否充足
                            dic = new Dictionary<string, string>();
                            dic.Add("LOCATOR_CODE",strparm.location_code);
                            dic.Add("ITEM_NUMBER", row["material_code"].ToString());
                            string sqlstr = MethodHelp.GetTranSQL("TMS0139", dic, con);//查询ERP库存校验,MYSQL获取语句
                            if (sqlstr != "")
                            {
                                DataTable dt_cb = DB.OracleQuery(sqlstr, gz_con);
                                if (dt_cb.Rows.Count>0) 
                                {
                                    if (DB.ToDouble(dt_cb.Rows[0]["QTY"].ToString()) < DB.ToDouble(row["ship_qty"].ToString()))
                                    {
                                        strMsg = strMsg + "_" + "货位=<" + strparm.location_code + ">,物料编码=<" + row["material_code"].ToString() + ">,需求数量=<" + row["ship_qty"].ToString() + "" +
                                            ">,ERP库存=<" + dt_cb.Rows[0]["QTY"].ToString() + ">,库存不足！";
                                    }
                                }
                                else
                                {
                                    strMsg = strMsg + "_"+ "货位=<" + strparm.location_code + ">,物料编码=<" + row["material_code"].ToString() + ">ERP找不到相关库存数据！";
                                }
                            }

                        }

                        //库存充足后，往下一步进行
                        if (strMsg=="")
                        {
                            //每个料号进行先进先出计算
                            foreach (DataRow row in hz_dt.Rows)
                            {
                                dic = new Dictionary<string, string>();
                                dic.Add("LOCATOR_CODE", strparm.location_code);
                                dic.Add("ITEM_NUMBER", row["material_code"].ToString());
                                string sqlstr = MethodHelp.GetTranSQL("TMS0141", dic, con);//查询ERP库存校验,MYSQL获取语句
                                if (sqlstr != "")
                                {
                                    DataTable dt_cb = DB.OracleQuery(sqlstr, gz_con);
                                    if (dt_cb.Rows.Count>0)
                                    {
                                        //获取外协挑库单，同料号记录进行运算
                                        dic = new Dictionary<string, string>();
                                        dic.Add("shipment_no", strparm.shipment_no);
                                        dic.Add("material_code", row["material_code"].ToString());
                                        DataTable mt_dt = MethodHelp.GetTableInfo("TMS0140", dic, con);
                                        if (mt_dt.Rows.Count > 0)
                                        {
                                            foreach (DataRow item in mt_dt.Rows)
                                            {
                                                double re_qty = DB.ToDouble(item["ship_qty"].ToString());
                                                for (int i = 0; i < dt_cb.Rows.Count; i++)
                                                {
                                                    if (re_qty>0)
                                                    {
                                                        //当前需求数量少于等于未分配数量，当前已分配行=已分配数量+需求数量
                                                        if (re_qty <= DB.ToDouble(dt_cb.Rows[i]["QTY"].ToString()) - DB.ToDouble(dt_cb.Rows[i]["FP_QTY"].ToString()))
                                                        {

                                                            details.Add(new ERPGetStockOutPutResponseData
                                                            {
                                                                shipment_no = strparm.shipment_no,
                                                                warehouse_code = dt_cb.Rows[i]["SUBINVENTORY_CODE"].ToString(),
                                                                location_code = dt_cb.Rows[i]["LOCATOR_CODE"].ToString(),
                                                                location_name = dt_cb.Rows[i]["LOCATOR_DESC"].ToString(),
                                                                material_code = dt_cb.Rows[i]["ITEM_NUMBER"].ToString(),
                                                                material_name = dt_cb.Rows[i]["ITEM_DESC"].ToString(),
                                                                source_batch = dt_cb.Rows[i]["LOT_NUMBER"].ToString(),
                                                                material_amount = re_qty,
                                                                saleorder_no = item["saleorder_no"].ToString(),
                                                                saleorderline_no = item["saleorderline_no"].ToString(),
                                                                plan_id = item["plan_no_id"].ToString()
                                                            });

                                                            dt_cb.Rows[i]["FP_QTY"] = (DB.ToDouble(dt_cb.Rows[i]["FP_QTY"].ToString()) + re_qty);
                                                            re_qty = 0;
                                                        }
                                                        else
                                                        {
                                                            //当前需求数量大于未分配数量，当前已分配行=已分配数量+未分配数量
                                                            details.Add(new ERPGetStockOutPutResponseData
                                                            {
                                                                shipment_no = strparm.shipment_no,
                                                                warehouse_code = dt_cb.Rows[i]["SUBINVENTORY_CODE"].ToString(),
                                                                location_code = dt_cb.Rows[i]["LOCATOR_CODE"].ToString(),
                                                                location_name = dt_cb.Rows[i]["LOCATOR_DESC"].ToString(),
                                                                material_code = dt_cb.Rows[i]["ITEM_NUMBER"].ToString(),
                                                                material_name = dt_cb.Rows[i]["ITEM_DESC"].ToString(),
                                                                source_batch = dt_cb.Rows[i]["LOT_NUMBER"].ToString(),
                                                                material_amount = DB.ToDouble(dt_cb.Rows[i]["QTY"].ToString()) - DB.ToDouble(dt_cb.Rows[i]["FP_QTY"].ToString()),
                                                                saleorder_no = item["saleorder_no"].ToString(),
                                                                saleorderline_no = item["saleorderline_no"].ToString(),
                                                                plan_id = item["plan_no_id"].ToString()
                                                            });

                                                            re_qty = re_qty - (DB.ToDouble(dt_cb.Rows[i]["QTY"].ToString()) - DB.ToDouble(dt_cb.Rows[i]["FP_QTY"].ToString()));//先处理需求数量,需求数量减去当前行未分配数量 
                                                            dt_cb.Rows[i]["FP_QTY"] = DB.ToDouble(dt_cb.Rows[i]["FP_QTY"].ToString()) + (DB.ToDouble(dt_cb.Rows[i]["QTY"].ToString()) - DB.ToDouble(dt_cb.Rows[i]["FP_QTY"].ToString()));//当前行已分配数量+上未分配数量
                                                               
                                                        }
                                                    }
                                                    else
                                                    {
                                                        break;
                                                    }
                                                   
                                                }
                                            }
                                        }
                                    }
                                }

                            }
                            if (details.Count>0)
                            {
                                re.data = details;
                            }
                        }

                       
                    }
                    else
                    {
                        strMsg = "外协挑库单=<"+ strparm.shipment_no + ">找不到有效订单明细记录，请确认后再试！";
                    }


                 
                }               
            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }
            if (strMsg=="")
            {
                re.code = 0;
                re.message = "";
            }
            else
            {
                re.code = 500;
                re.message = strMsg;
            }

            _logger.LogInformation(JsonConvert.SerializeObject(re));
            return new JsonResult(re);
        }

      
    }
}
